package com.loeng.framework.apilog.config;

import com.loeng.framework.apilog.core.filter.ApiAccessLogFilter;
import com.loeng.framework.apilog.core.interceptor.ApiAccessLogInterceptor;
import com.loeng.framework.common.enums.WebFilterOrderEnum;
import com.loeng.framework.web.config.LoengWebAutoConfiguration;
import com.loeng.framework.web.config.WebProperties;
import com.loeng.module.infra.api.logger.ApiAccessLogApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;

/**
 * API 访问日志 AutoConfiguration
 *
 * @author loeng zhuo
 */
@AutoConfiguration(after = LoengWebAutoConfiguration.class)
public class LoengApiLogAutoConfiguration implements WebMvcConfigurer {

    /**
     * 创建 API 访问日志的 Filter
     * ConditionalOnProperty: 允许使用 loeng.access-log.enable=false 禁用访问日志
     * @param webProperties Web 配置项
     * @param applicationName 应用名
     * @param apiAccessLogApi API 访问日志的 API
     * @return FilterRegistrationBean
     */
    @Bean
    @ConditionalOnProperty(prefix = "loeng.access-log", value = "enable", matchIfMissing = true)
    public FilterRegistrationBean<ApiAccessLogFilter> apiAccessLogFilter(WebProperties webProperties,
                                                                         @Value("${spring.application.name}") String applicationName,
                                                                         ApiAccessLogApi apiAccessLogApi) {
        ApiAccessLogFilter filter = new ApiAccessLogFilter(webProperties, applicationName, apiAccessLogApi);
        return createFilterBean(filter, WebFilterOrderEnum.API_ACCESS_LOG_FILTER);
    }

    /**
     * 创建 API 访问日志的 Interceptor
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ApiAccessLogInterceptor());
    }

    private static <T extends Filter> FilterRegistrationBean<T> createFilterBean(T filter, Integer order) {
        FilterRegistrationBean<T> bean = new FilterRegistrationBean<>(filter);
        bean.setOrder(order);
        return bean;
    }

}
